package pwd.allen.writeHandler;

import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.alibaba.excel.write.handler.SheetWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
import com.alibaba.excel.write.property.ExcelWriteHeadProperty;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 按照指定的列去排
 *
 * 注意：
 *  1.需要借助includeColumnFiledNames，否则达不到效果
 *  2.不能指定@ExcelIgnore标注的字段，否则会是空列
 *
 * @author lenovo
 * @create 2020-06-16 17:13
 **/
public class SortSheetWriteHandler implements SheetWriteHandler {

    private List<String> listHead;

    public SortSheetWriteHandler(List<String> listHead) {
        this.listHead = listHead;
    }

    @Override
    public void beforeSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
    }

    @Override
    public void afterSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
        if (CollectionUtils.isEmpty(listHead)) {
            return;
        }

        ExcelWriteHeadProperty excelWriteHeadProperty = writeSheetHolder.getExcelWriteHeadProperty();
        Map<Integer, Head> headMap = excelWriteHeadProperty.getHeadMap();

        //<editor-fold desc="分析出要调整的下标">
        ArrayList<Integer> list_index = new ArrayList<>(listHead.size());
        for (String headStr : listHead) {
            Integer index = null;
            for (Map.Entry<Integer, Head> entry : headMap.entrySet()) {
                Head head = entry.getValue();
                if (head.getFieldName().equals(headStr)) {
                    index = entry.getKey();
                    break;
                }
            }
            list_index.add(index);
        }
        //</editor-fold>

        //<editor-fold desc="调整表头顺序">
        HashMap<Integer, Head> headMap_clone = new HashMap<>(headMap);
        headMap.clear();
        for (int i = 0; i < list_index.size(); i++) {
            Integer index = list_index.get(i);
            if (index != null) {
                headMap.put(i, headMap_clone.get(index));
            }
        }
        headMap_clone.clear();
        //</editor-fold>

        //<editor-fold desc="调整内容顺序">
        Map<Integer, ExcelContentProperty> contentPropertyMap = excelWriteHeadProperty.getContentPropertyMap();
        HashMap<Integer, ExcelContentProperty> propertyMap_clone = new HashMap<>(contentPropertyMap);
        contentPropertyMap.clear();
        for (int i = 0; i < list_index.size(); i++) {
            Integer index = list_index.get(i);
            if (index != null) {
                contentPropertyMap.put(i, propertyMap_clone.get(index));
            }
        }
        propertyMap_clone.clear();
        //</editor-fold>
    }
}
